import { getRoutes } from '@/api/menu'
import Layout from '@/layout'

const constantRouterComponents = {
  'Layout': Layout
}

/**
 * 3.
 * Dynamically generate menu
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = () => {
  return new Promise((resolve, reject) => {
    getRoutes().then(({ data }) => {
      const routers = generator(data)
      resolve(routers)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    const { title, path, redirect, component, icon, perms } = item || {}
    const currentRouter = {
      path: path || `${parent && parent.path || ''}/${name}`,
      name: title,
      // 导入组件   es6支持安装  babel-plugin-syntax-dynamic-import
      // component: constantRouterComponents[component || name] || (() => import(`@/views/${component}`)),
      component: constantRouterComponents[component || name] || ((resolve) => require([`@/views/${component}`], resolve)),
      meta: {
        title: title,
        icon: icon || undefined,
        permission: perms
      }
    }
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    item.redirect && (currentRouter.redirect = redirect)
    // 是否有子菜单
    if (item.children && item.children.length > 0) {
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}
